package com.alibaba.cloud.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.cloud.application.handler.MessageEventFactory;
import com.alibaba.cloud.application.handler.MessageEventHandler;
import com.alibaba.cloud.domain.MessageEvent;
import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import com.lmax.disruptor.util.DaemonThreadFactory;

import lombok.RequiredArgsConstructor;

/***
 * @description: 配置
 * @author: zhb1316783262@163.com
 * @date: 2022/6/27 22:13
 */
@Configuration
@EnableConfigurationProperties(value = {DisruptorProperties.class})
@ConditionalOnProperty(prefix = "disruptor", value = "enable", matchIfMissing = true)
@RequiredArgsConstructor
public class DisruptorConfig {
    private final DisruptorProperties disruptorProperties;
    private final MessageEventHandler messageEventHandler;

    @Bean
    public RingBuffer<MessageEvent> MessageVoRingBuffer() {
        //指定ringbuffer字节大小，必须为2的N次方（能将求模运算转为位运算提高效率），否则将影响效率
        //单线程模式，获取额外的性能
        Disruptor<MessageEvent> disruptor = new Disruptor<MessageEvent>(
                new MessageEventFactory(),
                disruptorProperties.getBufferSize(),
                DaemonThreadFactory.INSTANCE,
                ProducerType.SINGLE,
                new BlockingWaitStrategy()
        );
        //设置事件业务处理器---消费者
        disruptor.handleEventsWith(messageEventHandler);
        // 启动disruptor线程
        disruptor.start();
        //获取ringbuffer环，用于接取生产者生产的事件
        return disruptor.getRingBuffer();
    }
}
